var websock = null; // websocket对象
var global_callback = null; // 回调方法
var _heart_rate_interval = null // 计时器
var _heart_rate = ''; //心跳间隔
var showFun = null;
// var serverPort = '5000';	//webSocket连接端口

//  当前IP地址
function getWebIP(){
	var curIP = window.location.hostname;
	return curIP;
}
 //初始化weosocket
function initWebSocket(url,fun){
    showFun = fun
    var wsuri = url;
    websock = new WebSocket(wsuri);
    websock.onmessage = function(e){
    	websocketonmessage(e);
    }
    websock.onclose = function(e){
    	websocketclose(e);
    }
    websock.onopen = function () {
	     websocketOpen();
	}
    //连接发生错误的回调方法
	websock.onerror = function () {
    showFun(false)
		console.log("WebSocket连接发生错误");
	}
}

// 实际调用的方法
function sendSock(agentData,callback){
    _heart_rate = agentData.data.heartbeat_interval > 0 ? agentData.data.heartbeat_interval :  60000
    global_callback = callback;
    if (websock.readyState === websock.OPEN) {
    	//若是ws开启状态
        websocketsend(agentData)
    }else if (websock.readyState === websock.CONNECTING) {
    	// 若是 正在开启状态，则等待1s后重新调用
        setTimeout(function () {
        	sendSock(agentData,callback);
        }, 1000);
    }else {
    	// 若未开启 ，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData,callback);
        }, 1000);
    }
}

//数据接收
function websocketonmessage(e){
    let data = JSON.parse(e.data)
    if(global_callback && data.cmd!== 'pong'){
        global_callback(data);
        // 登录开启心跳
        if(data.data.success){
            beginSendHeartBeat()
        }
    }
}
//心跳
function beginSendHeartBeat(){
    _heart_rate_interval = setInterval(res => {
        websocketsend({cmd: "ping"})
    }, _heart_rate);
}
//停止心跳
function close() {
    _heart_rate_interval && clearInterval(_heart_rate_interval);
}
//数据发送
function websocketsend(agentData){
    websock.send(JSON.stringify(agentData));
}

//关闭socket
function websocketclose(e){
    console.log("connection closed (" + e.code + ")");
    showFun(false)
}

function websocketOpen(e){
	console.log("连接成功");
    showFun(true)
}

export{sendSock,initWebSocket,close}
